package com.example.wxy.bbtapp.Service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;


import java.util.Date;
import java.util.Iterator;

import com.example.wxy.bbtapp.Common.BitmapCompare;
import com.example.wxy.bbtapp.Common.FileHelper;
import com.example.wxy.bbtapp.DeviceService.AppMonitorService;
import com.example.wxy.bbtapp.DeviceService.ScreenManager;
import com.example.wxy.bbtapp.DeviceService.ScreenShotService;
import com.example.wxy.bbtapp.Receivers.AppPacketTimerReceiver;
import com.example.wxy.bbtapp.Receivers.TimerReceiver;
import com.example.wxy.bbtapp.Receivers.UpdaterReceiver;
import com.example.wxy.bbtapp.Startup.AppSettings;
import com.example.wxy.bbtapp.Models.ClassTime;
import com.example.wxy.bbtapp.Models.CourseRecord.CourseRecord;
import com.example.wxy.bbtapp.Models.CourseRecord.ScreenshotRecord;

/**
 * Created by yons on 2017/9/5.
 * 服务总线
 */

public class ServiceBus {

    public static int Day = 0;
    public static int CourseIndex = 0;
    public static CourseRecord Current_CourseRecord = null;
    public static boolean DoEventing = false;

    public ServiceBus() {

    }

    public static void DoRecord(Context c) {
        Log.d(AppSettings.DebugTag, "timerService.callback");
        if (DoEventing) {
            // 如果当前正在处理下课后的事务就不做任何事
            return;
        }
        // 获取当前时间的课
        ClassTime ct = ClassTimeService.GetCurrentClass(c);

        if (Current_CourseRecord == null && ct != null) {
            // 如果当前变量里没课，而去数据库里查出来这个时间点应该有课，那就给变量赋课

            Log.d(AppSettings.DebugTag, "Current_CourseRecord == null && ct != null ");

            // 设置当前课程
            Current_CourseRecord = CourseRecordService.NewRecord(ct);
        }

        //
        // 判断当前上课状态
        //

        if(Current_CourseRecord == null && ct== null)
        {
            // 当前没课
            Log.d(AppSettings.DebugTag, " No Course ");
        }
        else if (Current_CourseRecord != null && (new Date().getTime() > Current_CourseRecord.getEndTime().getTime())) {
            // 如果变量里是有课的，而现在已经到下课时间了
            Log.d(AppSettings.DebugTag, " course down ");

            // 锁定不再截屏等操作，因为上传等工作可能比较消耗时间，所以这里做了锁，一旦锁上就不会在下一个检测周期做任何事情
            DoEventing = true;

            // 对比图片相似度
            Current_CourseRecord.setScreenRecords(CourseRecordService.ComparePic(Current_CourseRecord.getScreenRecords()));

            // 取最好的几张截图
            Current_CourseRecord.setScreenRecords(CourseRecordService.GetValidPic(Current_CourseRecord.getScreenRecords()));

            // 保存
            CourseRecordService.SaveDB(Current_CourseRecord);

            // 上传 下课后的1到5分钟之间的随机数
            int delay = (int) (Math.random() * 3) + 1;
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    // 上传
                    CourseRecordService.PostDB();
                }
            }, delay * 1000 * 60);

            // 当前课程置空
            Current_CourseRecord = null;
            Log.d(AppSettings.DebugTag, "Set Current Course Record null ");

            DoEventing = false;
        }
        else if (Current_CourseRecord != null) {
            // 如果当前是在上课的
            if (ScreenManager.getScreenInfo(c) && !ScreenManager.isHome(c)) {
                // 如果屏幕是亮的并且不在桌面
                Log.d(AppSettings.DebugTag, "in Courese and Screen Open");

                // 添加有效使用时长 添加的数量是检测的周期，默认为20秒
                Current_CourseRecord.setEffectiveHours(Current_CourseRecord.getEffectiveHours() + AppSettings.MonitorSecond);

                // 取任务
                Current_CourseRecord.setProcessRecords(AppMonitorService.getTopActivy(c, Current_CourseRecord.getProcessRecords(), Current_CourseRecord.getID()));

                Log.d(AppSettings.DebugTag, "AppMonitorService get App list");

                // 截屏
                ScreenShotService.Shot(Current_CourseRecord, c);
            }
        }
    }


    public void start(final Context c) {

        // 每一段时间执行一次记录
        Intent intent = new Intent(c, TimerReceiver.class);
        PendingIntent sendIntent = PendingIntent.getBroadcast(c, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),  AppSettings.MonitorSecond * 1000, sendIntent);

        // 每一个小时检查一次更新
        Intent intent_update = new Intent(c, UpdaterReceiver.class);
        PendingIntent updateIntent = PendingIntent.getBroadcast(c, 0, intent_update, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am_update = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
        am_update.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),AppSettings.UpdateSecond * 1000, updateIntent);

        // 心跳
        Intent intent_AppPack = new Intent(c, AppPacketTimerReceiver.class);
        PendingIntent AppPackIntent = PendingIntent.getBroadcast(c, 0, intent_AppPack, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am_AppPack = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
        am_AppPack.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), AppSettings.AppPacketSecond * 1000, AppPackIntent);

        // 每天6点以后就停止心跳和记录
        // 添加一次性定时到第二天7点，再由这个时间开始心跳和记录
    }

}
